import { getUserRoleColorByRoleValue, getUserRoleInfoByRoleValue } from '@/common/UserRole';
import { UpdateUser, UpdateUserMethods } from '@/pages/Admin/ManageUser/components/UpdateUser';
import {
  deleteUserByIdUsingDelete,
  getAllUsersUsingPost,
} from '@/services/student-management-system/yonghumokuai';
import { DownloadOutlined, SearchOutlined } from '@ant-design/icons';
import { Badge, Button, Form, Input, message, Modal, Space, Table, Tag } from 'antd';
import { AddOutline } from 'antd-mobile-icons';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';

const ManageUser: React.FC = () => {
  // 搜索初始化参数
  const initSearchParam = {
    name: '',
    current: 1,
    pageSize: 6,
    sortField: 'createTime',
    sortOrder: 'desc',
  };

  const [dataSource, setDataSource] = useState<API.UserVO[]>([]);
  const [queryParam, setQueryParam] = useState<API.QueryUserDTO>({ ...initSearchParam });
  const [total, setTotal] = useState<number>(0);
  const [open, setOpen] = useState<boolean>(false);
  const [editUserVO, setEditUserVO] = useState<API.UserVO>({});
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
  const [title, setTitle] = useState<string>('');
  const childRef = useRef<UpdateUserMethods>(null);

  // 点击编辑按钮
  const handleOnEdit = (user: API.UserVO) => {
    setOpen(true);
    setTitle('编辑');
    setEditUserVO(user);
  };

  const handleOnDelete = async (record: API.UserVO) => {
    const res = await deleteUserByIdUsingDelete({ id: record.id ?? -1 });
    if (res.code === 200) {
      message.success('删除成功');
      // 这里进行处理
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      await getUsers();
    } else {
      message.error('删除失败：' + res.msg);
    }
  };

  // 列元素
  const columns = [
    { title: 'ID', dataIndex: 'id' },
    { title: '用户名', dataIndex: 'username' },
    { title: '真实名称', dataIndex: 'realName' },
    {
      title: '角色',
      dataIndex: 'role',
      render: (text: number) => (
        <Tag color={getUserRoleColorByRoleValue(text)}>{getUserRoleInfoByRoleValue(text)}</Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (text: number) => (
        <Badge status={text === 1 ? 'success' : 'error'} text={text === 1 ? '启用' : '关闭'} />
      ),
    },
    { title: '手机号', dataIndex: 'phone' },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: '120px',
      render: (text: Date) => (
        <>
          <div>{moment(text).format('YYYY-MM-DD')}</div>
          <div>{moment(text).format('HH:mm:ss')}</div>
        </>
      ),
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      width: '120px',
      render: (text: Date) => (
        <>
          <div>{moment(text).format('YYYY-MM-DD')}</div>
          <div>{moment(text).format('HH:mm:ss')}</div>
        </>
      ),
    },
    {
      title: '更多',
      dataIndex: 'options',
      width: '120px',
      render: (_: any, record: API.UserVO) => (
        <Space>
          <Button size="small" variant="link" onClick={() => handleOnEdit(record)}>
            编辑
          </Button>
          <Button size="small" variant="link" danger onClick={() => handleOnDelete(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 分页获取用户列表数据
  const getUsers = async () => {
    const res = await getAllUsersUsingPost({ ...queryParam });
    if (res.code === 200) {
      message.success('获取数据成功');
      setTotal(res.data?.total ?? 0);
      setDataSource(res.data?.records ?? []);
    } else {
      message.error('获取数据失败：' + res.msg);
    }
  };

  // 点击搜索按钮
  const handleSearch = (values: API.QueryUserDTO) => {
    setQueryParam({ ...initSearchParam, ...values });
  };

  // 点击modal 的确定按钮
  const handleOk = async () => {
    setConfirmLoading(true);
    try {
      const success = await childRef.current?.submitForm();
      if (success) {
        setOpen(false);
        getUsers();
      }
    } catch (error) {
      message.error('提交数据有误，请检查后再提交');
    } finally {
      setConfirmLoading(false); // 无论成功还是失败都应重置loading状态
    }
  };

  // 点击取消按钮
  const handleCancel = () => setOpen(false);

  // 点击添加用户按钮
  const handleAddUser = () => {
    setOpen(true);
    setTitle('新增');
    setEditUserVO({});
  };

  // 监听 queryParam 搜索参数变量 搜索响应列表变化
  useEffect(() => {
    getUsers();
  }, [queryParam]);

  return (
    <>
      <div className="ManageUser">
        <Form
          name="searchForm"
          layout="inline"
          onFinish={handleSearch}
          initialValues={{ ...queryParam }}
        >
          <Form.Item name="id" label="学号">
            <Input style={{ width: 100 }} placeholder="请输入学号" />
          </Form.Item>
          <Form.Item name="username" label="用户名">
            <Input style={{ width: 120 }} placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item name="realName" label="姓名">
            <Input style={{ width: 100 }} placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item name="phone" label="手机号">
            <Input style={{ width: 120 }} placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item>
            <Button icon={<SearchOutlined />} type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
        </Form>

        <Space style={{ marginTop: 10, marginBottom: 5 }}>
          <Button icon={<AddOutline />} color="green" variant="solid" onClick={handleAddUser}>
            新增学生
          </Button>
          <Button icon={<DownloadOutlined />} color="green" variant="solid">
            Excel 导入
          </Button>
        </Space>

        <Table
          columns={columns}
          dataSource={dataSource}
          pagination={{
            total,
            current: queryParam.current,
            pageSize: queryParam.pageSize,
            onChange: (current, pageSize) => setQueryParam({ ...queryParam, current, pageSize }),
          }}
        />

        <Modal
          title={title}
          open={open}
          onOk={handleOk}
          confirmLoading={confirmLoading}
          onCancel={handleCancel}
        >
          <UpdateUser editUserVO={editUserVO} onCloseModal={handleCancel} ref={childRef} />
        </Modal>
      </div>
    </>
  );
};

export default ManageUser;
